package com.push.common.utils;

import java.lang.management.ManagementFactory;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.chrono.MinguoDate;
import java.util.*;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * 时间工具类
 *
 * @author yanxi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    //"2023-01-30T11:39:00-05:00"
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM",
            "yyyy.MM.dd G 'at' HH:mm:ss z", "EEE, MMM d, ''yy", "h:mm a",
            "hh 'o''clock' a, zzzz", "K:mm a, z", "yyyyy.MMMMM.dd GGG hh:mm aaa",
            "EEE, d MMM yyyy HH:mm:ss Z", "yyMMddHHmmssZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
            "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", "YYYY-'W'ww-u", "EEE, dd MMM yyyy HH:mm:ss z",
            "EEE, dd MMM yyyy HH:mm zzzz", "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss.SSSzzzz",
            "yyyy-MM-dd'T'HH:mm:sszzzz", "yyyy-MM-dd'T'HH:mm:ss z", "yyyy-MM-dd'T'HH:mm:ssz",
            "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HHmmss.SSSz", "yyyy-MM-dd",
            "yyyyMMdd", "dd/MM/yy", "dd-MM-yyyy", "yyyy年MM月dd日",
            "MM月dd日", "yyyy年M月d日", "M月d日", "M d, yyyy", "MMMMM dd, yyyy",
            "MM d, yyyy","MMM. dd, yyyy","MMM. d, yyyy","yyyy-MM-dd'T'HH:mm:ss-mm:ss","d MMM yyyy","dd MMM yyyy",
            "yyyy/MM/dd"

    };

    /**
     * 一天转化为小时。单位：小时
     */
    public static final int DAY_2_HOUR = 24;
    public static final int WEEK_2_DAY = 7;
    public static final long SECOND_LONG = 1000L;
    public static final long MINUTE_LONG = 60 * SECOND_LONG;
    public static final long HOUR_LONG = 60 * MINUTE_LONG;
    public static final long DAY_LONG = DAY_2_HOUR * HOUR_LONG;
    public static final long MONTH_LONG = 30 * DAY_LONG;
    public static final long YEAR_LONG = 365 * DAY_LONG;
    public static final String DATE_FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND = "yyyy/MM/dd HH:mm:ss";
    public static final String DATE_FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND2 = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_MONTH_DAY = "MM月dd日";
    public static final String DATE_FORMAT_HOUR_MINUTE = "HH:mm";
    public static final String DATE_FORMAT_YEAR_MONTH_DAY = "yyyyMMdd";
    public static final String DATE_FORMAT_YEAR_MONTH_DAY2 = "yyyy-MM-dd";
    public static final String DATE_FORMAT_YEAR_MONTH_DAY_STRING = "yy年MM月dd日";
    public static final String DATE_FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE = "yyyy-MM-dd HH:mm";
    public static final int ONE_HOUR_MINUTE_COUNT = 60;
    private static final String DateFormatRege = "(?:发布时间：|\\[|\\])|修改日期：|日期：|Available online |Published: |發佈日期：";

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            String dateStr = str.toString().trim().replaceAll(DateFormatRege,"").trim();
            if (dateStr.matches("^(\\d{2})(-|/|\\.)\\d{1,2}(-|/|\\.)(\\d{4})$")){
                String[] dateArr = dateStr.split("-|/|\\.");
                if (dateArr.length == 3){
                    dateStr = dateArr[2]+"-"+dateArr[1]+"-"+dateArr[0];
                } else if (dateArr.length == 2){
                    dateStr = dateArr[1]+"-"+dateArr[0];
                }
            }
            return parseDate(dateStr, Locale.ENGLISH, parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    public static Date parseDate(Object str, Locale locale)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            String dateStr = str.toString().trim().replaceAll(DateFormatRege,"").trim();
            if (dateStr.matches("^(\\d{2})(-|/|\\.)\\d{1,2}(-|/|\\.)(\\d{4})$")){
                String[] dateArr = dateStr.split("-|/|\\.");
                if (dateArr.length == 3){
                    dateStr = dateArr[2]+"-"+dateArr[1]+"-"+dateArr[0];
                } else if (dateArr.length == 2){
                    dateStr = dateArr[1]+"-"+dateArr[0];
                }
            }
            return parseDate(dateStr, locale, parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }


    public static Map<Integer,String> dayOfWeekMap = new HashMap(){{
        put(1, "一");
        put(2, "二");
        put(3, "三");
        put(4, "四");
        put(5, "五");
        put(6, "六");
        put(7, "日");
    }};
    public static Instant getInstant(){
        return  Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
    }
    /**
     * 当前时间
     *
     * @return
     */
    public static Date currentDate() {
        return Calendar.getInstance().getTime();
    }
    /**
     * @param date1 时间A
     * @param date2 时间B
     * @return 是否2个为同一天
     */
    public static boolean isSameDay(Date date1, Date date2) {
        return !(date1 == null || date2 == null) && diffDay(date1, date2) == 0;
    }

    //计算两个日期相差年数
    public static int diffYear(String startDate,String endDate) throws ParseException {
        Calendar calBegin = Calendar.getInstance(); //获取日历实例
        Calendar calEnd = Calendar.getInstance();
        calBegin.setTime(stringToDate(startDate,"yyyy"));
        calEnd.setTime(stringToDate(endDate,"yyyy"));
        return Math.abs(calEnd.get(Calendar.YEAR) - calBegin.get(Calendar.YEAR));
    }

    /**
     * 计算两个日期之间相差的天数.不包括今天。
     *
     * @param date1 时间A
     * @param date2 时间B
     * @return 时间A与时间B的差值(前者 - 后者)。当有任何一个时间为空时，返回null
     * @see #diffDay(Date, Date, boolean) 取代。
     * 原因：该方法不精准。
     */
    public static Integer diffDay(Date date1, Date date2) {
        return diffDay(date1, date2, false);
    }

    /**
     * 计算两个日期之间相差的天数
     *
     * @param fDate        时间A
     * @param oDate        时间B
     * @param includeToday 是否包括今天
     * @return 时间A与时间B的差值(前者 - 后者)。当有任何一个时间为空时，返回null
     */
    public static Integer diffDay(Date fDate, Date oDate, boolean includeToday) {
        if (fDate == null || oDate == null) {
            return null;
        }
        DateTime begin = new DateTime(fDate);
        DateTime end = new DateTime(oDate);
        int days = Days.daysBetween(end.toLocalDate(), begin.toLocalDate()).getDays();
        return includeToday ? days + 1 : days;
    }

    /**
     * 计算量个日期之间相差的小时数
     *
     * @param fDate       时间A
     * @param oDate       时间B
     * @param includeHour 是否包括当前小时
     * @return 时间A与时间B的差值(前者 - 后者)。当有任何一个时间为空时，返回null
     */
    @SuppressWarnings("UnusedDeclaration")
    public static Integer diffHour(Date fDate, Date oDate, boolean includeHour) {
        if (fDate == null || oDate == null) {
            return null;
        }
        DateTime begin = new DateTime(fDate);
        DateTime end = new DateTime(oDate);
        int hours = Hours.hoursBetween(end.toLocalDateTime(), begin.toLocalDateTime()).getHours();
        return includeHour ? hours + 1 : hours;
    }

    /**
     * 比较两个时间的分差
     * @param fDate 开始时间
     * @param oDate 结束时间
     * @return
     */
    public static Integer diffMinutes(Date fDate, Date oDate) {
        if (fDate == null || oDate == null) {
            return null;
        }
        DateTime begin = new DateTime(fDate);
        DateTime end = new DateTime(oDate);
        return Minutes.minutesBetween(begin.toLocalDateTime(), end.toLocalDateTime()).getMinutes();
    }

    /**
     * @param date 时间
     * @return 参数日期是否为今天
     */
    public static boolean isToday(Date date) {
        return isSameDay(date, new Date());
    }

    /**
     * 计算当期时间相差的日期
     *
     * @param field  日历字段.<br/>eg:Calendar.MONTH,Calendar.DAY_OF_MONTH,<br/>Calendar.HOUR_OF_DAY等.
     * @param amount 相差的数值
     * @return 计算后的日志
     */
    public static Date addDate(int field, int amount) {
        return addDate(null, field, amount);
    }

    /**
     * 计算当期时间相差的日期
     *
     * @param date   设置时间
     * @param field  日历字段.<br/>eg:Calendar.MONTH,Calendar.DAY_OF_MONTH,<br/>Calendar.HOUR_OF_DAY等.
     * @param amount 相差的数值
     * @return 计算后的日志
     */
    public static Date addDate(Date date, int field, int amount) {
        Calendar c = Calendar.getInstance();
        if (date != null) {
            c.setTime(date);
        }
        c.add(field, amount);
        return c.getTime();
    }

    /**
     * 设置指定时间的相关field
     *
     * @param date   设置时间
     * @param field  日历字段.<br/>eg:Calendar.MONTH,Calendar.DAY_OF_MONTH,<br/>Calendar.HOUR_OF_DAY等.
     * @param amount 设置的值
     * @return 计算后的日志
     */
    public static Date setDate(Date date, int field, int amount) {
        Calendar c = Calendar.getInstance();
        if (date != null) {
            c.setTime(date);
        }
        c.set(field, amount);
        return c.getTime();
    }

    /**
     * 设置指定时间的相关field
     *
     * @param date 时间
     * @param hour 小时，当null的时候，不进行改变
     * @param minute 分钟，当null的时候，不进行改变
     * @param second 秒，当null的时候，不进行改变
     * @param milliSecond 毫秒，当null的时候，不进行改变
     * @return 结果
     */
    public static Date setDate(Date date, Integer hour, Integer minute, Integer second, Integer milliSecond) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (hour != null) {
            calendar.set(Calendar.HOUR_OF_DAY, hour);
        }
        if (minute != null) {
            calendar.set(Calendar.MINUTE, minute);
        }
        if (second != null) {
            calendar.set(Calendar.SECOND, second);
        }
        if (milliSecond != null) {
            calendar.set(Calendar.MILLISECOND, milliSecond);
        }
        return calendar.getTime();
    }

    /**
     * 获取指定天结束时间
     *
     * @param date 日期
     * @return 获得该日期的开始
     */
    public static Date getDayBegin(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        setCalender(calendar, 0, 0, 0, 0);
        return calendar.getTime();
    }

    /**
     * 获取当天开始时间
     *
     * @return 获得该日期的开始
     */
    public static Date getDayBegin() {
        return getDayBegin(new Date());
    }

    /**
     * 获取指定天结束时间
     *
     * @param date 日期
     * @return 获得该日期的结束
     */
    public static Date getDayEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        setCalender(calendar, 23, 59, 59, 999);
        return calendar.getTime();
    }

    /**
     * 获取当天结束时间
     *
     * @return 获得该日期的开始
     */
    public static Date getDayEnd() {
        return getDayEnd(new Date());
    }

    /**
     * 指定时间是否是一天开始时间
     */
    public static boolean isDayBegin(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (calendar.get(Calendar.HOUR_OF_DAY) == 0 && calendar.get(Calendar.MINUTE) == 0 && calendar.get(Calendar.SECOND) == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 指定时间是否是一天结束时间
     */
    public static boolean isDayEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (calendar.get(Calendar.HOUR_OF_DAY) == 23 && calendar.get(Calendar.MINUTE) == 59 && calendar.get(Calendar.SECOND) == 59) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 指定时间是否是一天开始时间（严格模式，校验毫秒）
     */
    public static boolean isDayBeginStrictly(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (calendar.get(Calendar.HOUR_OF_DAY) == 0 && calendar.get(Calendar.MINUTE) == 0 && calendar.get(Calendar.SECOND) == 0 && calendar.get(Calendar.MILLISECOND) == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 指定时间是否是一天结束时间（严格模式，校验毫秒）
     */
    public static boolean isDayEndStrictly(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (calendar.get(Calendar.HOUR_OF_DAY) == 23 && calendar.get(Calendar.MINUTE) == 59 && calendar.get(Calendar.SECOND) == 59 && calendar.get(Calendar.MILLISECOND) == 999) {
            return true;
        } else {
            return false;
        }
    }

    public static Date getMinuteBegin(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        setCalender(calendar, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE),
                0, 0);
        return calendar.getTime();
    }

    public static Date getMinuteEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        setCalender(calendar, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE),
                59, 999);
        return calendar.getTime();
    }

    /**
     * 获取该时间所在的小时开始时间点
     */
    public static Date getHourBegin(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取该时间所在的小时结束时间点
     */
    public static Date getHourEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     * 获取该日期当月第一天
     *
     * @param date
     * @return
     */
    public static Date getMonthBegin(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getDayBegin(date));
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }

    /**
     * 获取该日期当月最后一天getAgeByBirthday
     *
     * @param date
     * @return
     */
    public static Date getMonthEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getDayEnd(date));
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        return calendar.getTime();
    }

    /**
     * 判断该日期为星期几？
     *
     * @param pTime   日期
     * @param pattern 时间格式化(若为空,则pattern 默认为 'yyyy/MM/dd HH:mm:ss')
     * @return 1-星期一,2-星期二,.....,6-星期六,7-星期天
     */
    public static Integer dayForWeek(String pTime, String pattern) throws Exception {
        if(StringUtils.isEmpty(pattern)){
            pattern = DATE_FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
        }
        Date date = parse(pTime, pattern);
        return dayForWeek(date);
    }

    // long转换为Date类型
    public static Date longToDate(long currentTime) {
        Date date = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间
        return date;
    }

    /**
     * 判断该日期为星期几？
     *
     * @param date   日期
     * @return 1-星期一,2-星期二,.....,6-星期六,7-星期天
     */
    public static Integer dayForWeek(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        Integer dayForWeek = 0;
        if(calendar.get(Calendar.DAY_OF_WEEK) == 1){
            dayForWeek = 7;
        }else{
            dayForWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }

    /**
     * 判断该日期为星期几
     *
     * @param date   日期
     * @return 一,二,.....,六,日
     */
    public static String dayForWeek2(Date date){
        Integer dayForWeek = dayForWeek(date);
        return dayOfWeekMap.get(dayForWeek);
    }

    /**
     * 获取几号
     * @param date
     * @return
     */
    public static Integer dayForMonth(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 取得日期所在周的下星期一<br />
     *      注：若参数date为空，则取得第当前日期所对应的下一周
     *
     * @param date 所在日期
     */
    public static Date getNextMonday(Date date) {
        Calendar cal = Calendar.getInstance();
        // 没有设置日期,则取当前时间
        if(date != null){
            cal.setTime(date);
        }
        int day = cal.get(Calendar.DAY_OF_WEEK);
        if(day != Calendar.SUNDAY){
            cal.add(Calendar.WEEK_OF_MONTH, 1);
        }
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        return cal.getTime();
    }

    /**
     * 取得日期所在周的下星期日<br />
     *      注：若参数date为空，则取得第当前日期所对应的下一周
     *
     * @param date 所在日期
     */
    public static Date getNextSunday(Date date) {
        Calendar cal = Calendar.getInstance();
        // 没有设置日期,则取当前时间
        if (date != null) {
            cal.setTime(date);
        }
        int day = cal.get(Calendar.DAY_OF_WEEK);

        if (day != Calendar.SUNDAY){
            cal.add(Calendar.WEEK_OF_MONTH, 2);
        } else {
            cal.add(Calendar.WEEK_OF_MONTH, 1);
        }
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return cal.getTime();
    }

    /**
     * 取得日期所在周的上个星期一<br />
     *      注：若参数date为空，则取得第当前日期所对应的上一周
     * @param date
     * @return
     */
    public static Date getBeforeWeekMonday(Date date){
        Calendar cal = Calendar.getInstance();
        if(date != null){
            cal.setTime(date);
        }
        //n为推迟的周数，1本周，-1向前推迟一周，2下周，依次类推
        int n = -1;
        String monday;
        cal.add(Calendar.DATE, n*7);

        //想周几，这里就传几Calendar.MONDAY（TUESDAY...）
        cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
        return cal.getTime();
    }

    /**
     * 取得日期所在月的上个月同一天<br />
     *      注：若参数date为空，则取得第当前月所对应的上一月
     * @param date
     * @return
     */
    public static Date getBeforeMonthDay(Date date){
        Calendar cal = Calendar.getInstance();
        if (date != null){
            cal.setTime(date);
        }
        cal.add(Calendar.MONTH, -1);
        return cal.getTime();
    }

    /**
     * 取得日期所在周的周末<br />
     *      注：若参数date为空，则取得第当前日期所对应的下一周
     * @param date
     * @return
     */
    public static Date getWeekEnd(Date date){
        Calendar cal = Calendar.getInstance();
        if(date != null){
            cal.setTime(date);
        }
        //n为推迟的周数，1本周，-1向前推迟一周，2下周，依次类推
        int n = 1;
        cal.add(Calendar.DATE, n * 7);

        //想周几，这里就传几Calendar.MONDAY（TUESDAY...）
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return cal.getTime();
    }

    /**
     * 取得日期所在的前一天
     *
     * @param date
     * @return
     */
    public static Date getDayBefore(Date date) {
        Calendar c = Calendar.getInstance();
        if(date != null){
            c.setTime(date);
        }
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - 1);
        return c.getTime();
    }

    /**
     * 取得所在日期的下一天<br/>
     *      注：如date为空,则取到为明天
     *
     * @param date 所在日期
     */
    public static Date getNextDay(Date date){
        Calendar calendar = Calendar.getInstance();
        if(date != null){
            calendar.setTime(date);
        }
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        return calendar.getTime();
    }

    /**
     * 获取日期的小时分钟字符串
     * @param date
     * @return
     */
    public static Integer getHourMinute(Date date){
        int beginHour = DateUtils.getField(date, Calendar.HOUR_OF_DAY);
        int beginMinute = DateUtils.getField(date,Calendar.MINUTE);
        Integer result = Integer.valueOf(String.valueOf(beginHour) + String.valueOf(beginMinute));
        return result;
    }

    /**
     * 获取日期所在月的天数
     * @param date
     * @return
     */
    public static int getDayAccountOfMonth(Date date){
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        if(date != null){
            calendar.setTime(date);
        }
        int day = calendar.getActualMaximum(Calendar.DATE);
        return day;
    }

    /**
     * 取得日期所在月的下个月同一天<br />
     *      注：若参数date为空，则取得第当前月所对应的下一月
     * @param date
     * @return
     */
    public static Date getNextMonthDay(Date date){
        Calendar cal = Calendar.getInstance();
        if (date != null){
            cal.setTime(date);
        }
        cal.add(Calendar.MONTH, 1);
        return cal.getTime();
    }

    /**
     * 设置Calendar的小时、分钟、秒、毫秒
     *
     * @param calendar    日历
     * @param hour        小时
     * @param minute      分钟
     * @param second      秒
     * @param milliSecond 毫秒
     */
    public static void setCalender(Calendar calendar, int hour, int minute, int second, int milliSecond) {
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.MILLISECOND, milliSecond);
    }

    /**
     * 格式化日期
     * @param date    时间。若为空，则返回空串
     * @param pattern 时间格式化
     * @param locale 本地化
     * @return 格式化后的时间字符串
     */
    public static String format(Date date, String pattern, Locale locale) {
        if (date == null) {
            return "";
        }
        return new SimpleDateFormat(pattern, locale).format(date);
    }

    public static Date parse(String date, String pattern) {
        try {
            return new SimpleDateFormat(pattern).parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param date 时间。不允许空
     * @return 时间对应的int值。比如说2013/3/4转换为20130304
     */
    public static Integer formatDate2Int(Date date) {
        Assert.notNull(date, "date is null!");
        return Integer.valueOf(format(date, "yyyyMMdd"));
    }

    /**
     * 将int形日期转为Date
     *
     * @param dateInt 日期int形式，如20150909
     */
    public static Date parseInt2Date(Integer dateInt) {
        return parse(String.valueOf(dateInt), DATE_FORMAT_YEAR_MONTH_DAY);
    }


    /**
     * @param year        年
     * @param mouth       月
     * @param day         日
     * @param hour        小时
     * @param minute      分钟
     * @param second      秒
     * @param milliSecond 毫秒
     * @return 指定时间
     */
    @SuppressWarnings("UnusedDeclaration")
    public static Date buildTime(Integer year, Integer mouth, Integer day, Integer hour, Integer minute,
                                 Integer second, Integer milliSecond) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, mouth - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.MILLISECOND, milliSecond);
        return calendar.getTime();
    }

    /**
     * 判断当时时间是否在某个时间范围内
     *
     * @param minHour
     * @param minMin
     * @param maxHour
     * @param maxMin
     * @return
     */
    public static boolean isBetweenTheTimeZone(int minHour, int minMin, int maxHour, int maxMin) {
        return isBetweenTheTimeZone(minHour * 100 + minMin, maxHour * 100 + maxMin);
    }

    public static boolean isBetweenTheTimeZone(int beginTime, int endTime) {
        return isBetweenTheTimeZone(null, beginTime, endTime);
    }

    public static boolean isBetweenTheTimeZone(Date date, int beginTime, int endTime) {
        Calendar calendar = Calendar.getInstance();
        if (date != null) {
            calendar.setTime(date);
        }
        int now = calendar.get(Calendar.HOUR_OF_DAY) * 100 + calendar.get(Calendar.MINUTE);
        return beginTime <= now && now <= endTime;
    }

    /**
     * 获得时间指定的field
     * @param time 时间
     * @param field filed
     * @return 值
     */
    public static int getField(Date time, int field) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        return calendar.get(field);
    }

    /**
     * 获取两个时间质监相差几秒
     * @param oldTime
     * @param newTime
     * @return
     */
    public static int diffSeconds(Date oldTime,Date newTime){
        Long time1 = oldTime.getTime();
        Long time2 = newTime.getTime();
        Long seconds = (time2 - time1)/1000;
        return seconds.intValue();
    }

    /**
     * 转换成当天该时分秒下的Date日期
     * @param time 格式 "HH:mm:ss"
     * @return Date 格式 "yyyy-MM-dd HH:mm:ss"
     */
    public static Date setTime (String time) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = dateFormat.format(new Date());
        currentDate = currentDate + " " + time;
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return dateFormat.parse(currentDate);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 当前系统时间+分钟数 得到新的时间
     * @param minutes
     * @return
     */
    public static Date currentTimePlusMinutes(Long minutes) {
        Long currentTime = System.currentTimeMillis() + minutes * 60 * 1000;
        return new Date(currentTime);
    }

    /**
     * 转换为小时
     * @param minute 分钟/秒数
     * @param timeType 1：分钟 2：秒
     * @return
     */
    public static String calculateTime(Integer minute, Integer timeType){
        if(minute == null){
            return "0";
        }
        if(timeType == null){
            timeType = 1;
        }
        if(timeType == 1){
            if(minute >= 0 && minute < 60){
                return minute + "分钟";
            }
            if(minute >= 60 && minute < 1440){
                return minute / 60 + "小时" + minute % 60 + "分钟";
            }
            if(minute >= 1440){
                return minute / 1440 + "天" + minute % 1440 / 60 + "小时" + minute % 1440 % 60 + "分钟";
            }
        } else if (timeType == 2){
            if(minute >= 0 && minute < 3600){
                return minute / 60 + "分钟";
            }
            if(minute >= 3600 && minute < 5184000){
                return minute / 3600 + "小时" + minute % 3600 + "分钟";
            }
            if(minute >= 5184000){
                return minute / 5184000 + "天" + minute % 5184000 / 3600 + "小时" + minute % 5184000 % 3600 + "分钟";
            }
        }
        return "0";
    }

    /**
     * 根据用户生日计算年龄
     */
    public static int getAgeByBirthday(Date birthday) {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthday)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        cal.setTime(birthday);
        int yearBirth = cal.get(Calendar.YEAR);
        int age = yearNow - yearBirth+1;

        return age;
    }


    /**
     * 根据用户生日计算具体年龄 岁/月/天
     */
    public static String getSpecificAgeByBirthday(Date birthday) {
        Calendar cal = Calendar.getInstance();
        Calendar ca2 = Calendar.getInstance();
        if (cal.before(birthday)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        ca2.setTime(birthday);
        int yearBirth = ca2.get(Calendar.YEAR);
        int age = yearNow - yearBirth;
        if (age == 0) {
            int mouthNow = cal.get(Calendar.MONTH);
            ca2.setTime(birthday);
            int mouthBirth = ca2.get(Calendar.MONTH);
            age = mouthNow - mouthBirth;
            if (age == 0) {
                int dayNow = cal.get(Calendar.DAY_OF_MONTH);
                ca2.setTime(birthday);
                int dayBirth = ca2.get(Calendar.DAY_OF_MONTH);
                age = dayNow - dayBirth;
                return age + "天";
            } else if (age > 0) {
                return age + "月";
            }
        } else if (age > 0) {
            return age + "岁";
        }
        return null;
    }

    /**
     * 是否在指定时间段之间
     *
     * @param judgeTime
     * @param beginTime
     * @param endTime
     * @param flag      0-[beginTime<=judgeTime<=endTime]
     *                  1-[beginTime<judgeTime<=endTime]
     *                  2-[beginTime<=judgeTime<endTime]
     *                  3-[beginTime<judgeTime<endTime]
     * @return
     */
    public static boolean isBetweenTimes(Date judgeTime, Date beginTime, Date endTime, int flag) {
        switch (flag) {
            case 0:
                return (beginTime.getTime() <= judgeTime.getTime() && judgeTime.getTime() <= endTime.getTime());
            case 1:
                return (beginTime.getTime() < judgeTime.getTime() && judgeTime.getTime() <= endTime.getTime());
            case 2:
                return (beginTime.getTime() <= judgeTime.getTime() && judgeTime.getTime() < endTime.getTime());
            case 3:
                return (beginTime.getTime() < judgeTime.getTime() && judgeTime.getTime() < endTime.getTime());
        }
        return false;
    }

    /**
     * 获得本周一的日期
     * @return
     */
    public static String getMondayOFWeek() {
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String preMonday = sdf.format(currentDate.getTime());
        return preMonday;
    }

    /**
     * 获得当前日期与本周日相差的天数
     * @return
     */
    private static int getMondayPlus() {
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1;         //因为按中国礼拜一作为第一天所以这里减1
        if (dayOfWeek == 1) {
            return 0;
        } else {
            return 1 - dayOfWeek;
        }
    }

    /**
     * 上月第一天
     * @return
     */
    public static String getPreviousMonthFirst() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DATE, 1);//设为当前月的1号
        lastDate.add(Calendar.MONTH, -1);//减一个月，变为下月的1号
        //lastDate.add(Calendar.DATE,-1);//减去一天，变为当月最后一天

        str = sdf.format(lastDate.getTime());
        return str;
    }

    /**
     * 获得上月最后一天的日期
     * @return
     */
    public static String getPreviousMonthEnd() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.MONTH, -1);//减一个月
        lastDate.set(Calendar.DATE, 1);//把日期设置为当月第一天
        lastDate.roll(Calendar.DATE, -1);//日期回滚一天，也就是本月最后一天
        str = sdf.format(lastDate.getTime());
        return str;
    }

    /**
     * 当前日期
     * @param day 加减天
     * @return
     */
    public static String operDay(int day){
        Date date = new Date();//当前日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");//格式化对象
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(date);//设置当前日期
        calendar.add(Calendar.DAY_OF_MONTH, day);//月份加、减
        return format.format(calendar.getTime());
    }

    /**
     * 获得上一个小时
     * @return
     */
    public static String getPreviousHour() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("HH");

        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.HOUR, -1);
        str = sdf.format(lastDate.getTime());
        return str;
    }
    /**
     * 获得当前时间时分秒
     * @return
     */
    public static String getCurrentMinutesandSeconds() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.HOUR, -1);
        str = sdf.format(lastDate.getTime());
        return str;
    }
    public static Date parse(String str) {
        DateFormat format = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /*
     * date类型转换为String类型
     * formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
     * data Date类型的时间
     */
    public static String dateToString(Date data, String formatType) {
        return new SimpleDateFormat(formatType).format(data);
    }
    /*
     * long类型转换为String类型
     * currentTime要转换的long类型的时间
     * formatType要转换的string类型的时间格式
     */
    public static String longToString(long currentTime, String formatType)
            throws ParseException {
        Date date = longToDate(currentTime, formatType); // long类型转成Date类型
        String strTime = dateToString(date, formatType); // date类型转成String
        return strTime;
    }
    /*
     * string类型转换为date类型
     * strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
     * HH时mm分ss秒，
     * strTime的时间格式必须要与formatType的时间格式相同
     */
    public static Date stringToDate(String strTime, String formatType)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }
    /*
     * long转换为Date类型
     * currentTime要转换的long类型的时间
     * formatType要转换的时间格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
     */
    public static Date longToDate(long currentTime, String formatType)
            throws ParseException {
        Date dateOld = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间
        String sDateTime = dateToString(dateOld, formatType); // 把date类型的时间转换为string
        Date date = stringToDate(sDateTime, formatType); // 把String类型转换为Date类型
        return date;
    }

    /*
     * string类型转换为long类型
     * strTime要转换的String类型的时间
     * formatType时间格式
     * strTime的时间格式和formatType的时间格式必须相同
     */
    public static long stringToLong(String strTime, String formatType)
            throws ParseException {
        Date date = stringToDate(strTime, formatType); // String类型转成date类型
        if (date == null) {
            return 0;
        } else {
            long currentTime = dateToLong(date); // date类型转成long类型
            return currentTime;
        }
    }

    /*
     * date类型转换为long类型
     * date要转换的date类型的时间
     */
    public static long dateToLong(Date date) {
        return date.getTime();
    }

    /*
     *
     */
    public static Date addDate(Date date,int days) {
        if (null == date) {
            return date;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);   //设置当前日期
        c.add(Calendar.DATE, days); //日期加1天
        date = c.getTime();
        return date;
    }

    /*
     * 系统时间与计算时间戳之间相隔了几分钟
     * 取绝对值
     */
    public static int timeDifference(Long timestamp) {
        return (int) Math.abs(  System.currentTimeMillis() - timestamp ) / (1000 * 60);
    }

    //客户端时间和服务器时间差一个小时，则无法通过
    public static boolean isEffectiveTime(Long appTime){
        if(appTime!=null){
            if(appTime.toString().length() == 10){//处理10位时间戳
                int m = DateUtils.timeDifference(appTime*1000);
                if(Math.abs(m)<=60){
                    return true ;
                }
            } else {//如果是13位的
                int m = DateUtils.timeDifference(appTime);
                if(Math.abs(m)<=60){
                    return true ;
                }
            }

        }
        return false ;
    }

    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String getDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }

    /**
     * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        if (date == null) {
            return null;
        }
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }

    public static String formatDate(Date date, String dateStr, Object... pattern) {
        if (date == null) {
            return null;
        }
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }

    public static String formatTwDate(String dateStr) {
        if (com.push.common.utils.StringUtils.isEmpty(dateStr)){
            return null;
        }
        if (com.push.common.utils.StringUtils.countString(dateStr, "-") != 2){
            return null;
        }
        MinguoDate minguo2 = MinguoDate.of(Integer.valueOf(dateStr.substring(0,dateStr.indexOf("-"))), Integer.valueOf(dateStr.substring(dateStr.indexOf("-")+1, dateStr.lastIndexOf("-"))), Integer.valueOf(dateStr.substring(dateStr.lastIndexOf("-")+1)));
        LocalDate localDate2 = LocalDate.from(minguo2);
        return localDate2.toString();
    }

    /**
     * 得到日期时间字符串，转换格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String formatDateTime(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String getDateTime() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前年份字符串 格式（yyyy）
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * 得到当前月份字符串 格式（MM）
     */
    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    /**
     * 得到当天字符串 格式（dd）
     */
    public static String getDay() {
        return formatDate(new Date(), "dd");
    }

    /**
     * 得到当前星期字符串 格式（E）星期几
     */
    public static String getWeek() {
        return formatDate(new Date(), "E");
    }

    /**
     * 获取过去的天数
     *
     * @param date
     * @return
     */
    public static long pastDays(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (24 * 60 * 60 * 1000);
    }

    /**
     * 获得当前时间的字符串类型
     * @return
     */
    public static String toStr() {
        return toStr(new Date());
    }

    /**
     * Date转成"yyyy-MM-dd HH:mm:ss"格式的字符串
     * @param date
     * @return
     */
    public static String toStr(Date date) {
        return format(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 将一个 Date 格式化为日期/时间字符串
     * @param date 要格式化为时间字符串的时间值
     * @param pattern 日期和时间格式的模式
     * @return 已格式化的时间字符串
     */
    public static String format(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * 获取过去的小时
     *
     * @param date
     * @return
     */
    public static long pastHour(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (60 * 60 * 1000);
    }

    /**
     * 获取过去的分钟
     *
     * @param date
     * @return
     */
    public static long pastMinutes(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (60 * 1000);
    }

    /**
     *  将毫秒值转换为时间（天,时:分:秒.毫秒）
     *
     * @param timeMillis
     * @return
     */
    public static String formatDateTime(long timeMillis) {
        long day = timeMillis / (24 * 60 * 60 * 1000);
        long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
        long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
        return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
    }

    /**
     * 获取两个日期之间的天数
     *
     * @param before
     * @param after
     * @return
     */
    public static double getDaysBetweenDate(Date before, Date after) {
        return getMillisecBetweenDate(before,after) / (1000 * 60 * 60 * 24);
    }

    /**
     * 获取两个日期之间的毫秒数
     * @param before
     * @param after
     * @return
     */
    public static long getMillisecBetweenDate(Date before, Date after){
        long beforeTime = before.getTime();
        long afterTime = after.getTime();
        return afterTime - beforeTime;
    }

    /**
     * 获取当前月的第一天
     * @return
     */
    public static String getFirstDayOfMonth() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前月第一天：
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        String first = format.format(c.getTime());
        return first;
    }

    /**
     * 获得当前时间的时间戳
     * @return
     */
    public static Timestamp getTimestamp() {
        return new Timestamp(new Date().getTime());
    }

    /**
     *
     * 方法名: getDoubleType
     * 描述: 返回时间的 double
     * 参数: @param dateString
     * 参数: @return
     * 参数: @throws ParseException    设定文件
     */
    public static double getDoubleType(String dateString) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(dateString);
        return date.getTime();
    }


    /**
     * 获得两个Date之间的秒数
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    public static int calLastedTime(Date startTime, Date endTime) {
        long a = startTime.getTime();
        long b = endTime.getTime();
        int c = (int) ((a - b) / 1000);
        return c;
    }

    /**
     * 获取若干个小时之后的时间（字符串类型）
     * @param startTime
     * @param hours
     * @return
     */
    public static String getPassHours(String startTime, int hours) {
        // 获取一个小时以后的时间
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = df.parse(startTime);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + hours);
        return df.format(calendar.getTime());
    }


    /**
     * "yyyy-MM-dd HH:mm:ss"格式的日期在若干天数后的时间（字符串）
     * @param time
     * @param days
     * @return
     */
    public static String getAddDate(String time,int days) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = dateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        } // 指定日期
        Date newDate = null;
        newDate = addDate(date, days);
        String st = dateFormat.format(newDate);
        return st;
    }

    /**
     * 指定时间在若干天后的时间
     * @param date
     * @param day
     * @return
     * @throws ParseException
     */
    public static Date addDate(Date date,long day) throws ParseException {
        long time = date.getTime(); // 得到指定日期的毫秒数
        day = day*24*60*60*1000; // 要加上的天数转换成毫秒数
        time+=day; // 相加得到新的毫秒数
        return new Date(time); // 将毫秒数转换成日期
    }

    /**
     * 获取当天的某一时刻Date
     * @param hour      24小时
     * @param min       分钟
     * @param sec       秒
     * @param mill      毫秒
     * @return
     */
    public static Date getMoment(int hour,int min,int sec,int mill){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY,hour);
        calendar.set(Calendar.MINUTE,min);
        calendar.set(Calendar.SECOND,sec);
        calendar.set(Calendar.MILLISECOND,mill);
        return calendar.getTime();
    }

    /**
     * 获得指定某年某月某日某刻的Date
     * @param year      年
     * @param month 月
     * @param day       日
     * @param hour      24小时制
     * @param min       分钟
     * @param sec       秒
     * @param mill      毫秒
     * @return
     */
    public static Date getMoment(int year,int month,int day,int hour,int min,int sec,int mill){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.MONTH,month);
        calendar.set(Calendar.DAY_OF_MONTH,day);
        calendar.set(Calendar.HOUR_OF_DAY,hour);
        calendar.set(Calendar.MINUTE,min);
        calendar.set(Calendar.SECOND,sec);
        calendar.set(Calendar.MILLISECOND,mill);
        return calendar.getTime();
    }
    /*
     * 该方法用于比较两个用字符串表示的日期
     * param Date1, Date2 要求的格式为'yyyy-mm-dd'
     * 返回值为两个日期相差的天数
     */
    public static int compareDate(Date date1, Date date2){
        int returnVal = 0;
        try {
            returnVal = (int) ((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnVal;
    }
    /*
     * 该方法用于比较两个用字符串表示的日期
     * param Date1, Date2 要求的格式为'yyyy-mm-dd'
     * 返回值为两个日期相差的天数
     */
    public static int compareMinute(Date date1, Date date2){
        int returnVal = 0;
        try {
            returnVal = (int) ((date2.getTime() - date1.getTime()) / (1000 * 60));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnVal;
    }

    public static long getTimeInMillis(){
        return System.currentTimeMillis();
    }

    public static String getGMT() {
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("EEE, MMM d yyyy HH:mm:ss z+0800", Locale.ENGLISH);
        df.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // modify Time Zone.
        return (df.format(date));
    }
}
